/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { forwardRef, useState, useEffect } from 'react';
import { Select } from 'antd';
import { isLegalData } from '@/utils/utils';

const { Option } = Select;

/**
 * @param request 异步请求方法
 * @param format key * value 键值对名称
 * @param {Function} label 自定义渲染每一个option内容
 * @param dependency 请求更新的依赖
 *  */
const KbSelect = forwardRef((props, ref) => {
  const { request, format, children, label, dependency } = props;

  const [options, setOptions] = useState([]);

  const renderOption = (formatStr = 'key*value', arr = [], labelRender) => {
    const [key, value] = formatStr.split('*') || [];
    return arr.map((val, index) => (
      <Option key={val[key] || index} value={val[key] || val} option={val}>
        {labelRender ? labelRender(val) : val[value] || val[key]}
      </Option>
    ));
  };

  const filterOption = (input, option) =>
    option.props.children && option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;

  useEffect(
    () => {
      if (request) {
        const getOptions = async () => {
          const list = await request();
          setOptions(isLegalData(list));
        };
        getOptions();
      }
    },
    [dependency],
  );

  return (
    <Select filterOption={filterOption} {...props} ref={ref}>
      {children || renderOption(format, options, label)}
    </Select>
  );
});

export default KbSelect;
